package com.xdw.vuebackdemo.config;


/**
 * @author xiadewang
 * 解决跨域问题
 */
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AccessControlAllowOriginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Headers","requesttype");   //添加自定义的头部，多个就用，隔开这里不设置的话ajax无法添加自定义header
//        response.setHeader("Access-Control-Allow-Origin","http://localhost:3030");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-App-Id, X-Token");
        response.setHeader("Access-Control-Allow-Headers", "token,userid");
        //对于OPTIONS的请求放行
        if (((HttpServletRequest) req).getMethod().equals(RequestMethod.OPTIONS.name())) {

            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, response);
        }
    }

    public void init(FilterConfig filterConfig) {

    }

    public void destroy() {

    }

}
